﻿---
--- Author: NieQiang
--- User: CAPTAIN
--- CreateTime: 2024-9-2
--- Desc: Redis操作
---
local RedisTemplate = {}
local redis = require "resty.redis"

-- 初始化连接
local function initConnect()
  local host = "127.0.0.1"; -- 链接地址
  local port = 6379; -- 链接端口
  local password = "nieqiang@01" -- Redis密码
  local dbNum = 1; -- 数据库索引
  local r = redis:new()
  --r:set_keepalive(1000 * 10, 100);

  r:set_timeouts(1000, 1000, 1000)
  local ok, error = r:connect(host, port)

  if not ok then
    ngx.log(ngx.ERR, "链接失败: ", error)
    r:close(); -- 关闭连接
    return nil;
  end

  local resp, err = r:auth(password)
  if not resp then
    ngx.log(ngx.ERR, "认证失败: ", err)
    r:close(); -- 关闭连接
    return nil;
  end

  r:select(dbNum); -- 选择数据库

  return r;
end

-- 关闭连接
local function closeConnect(red)
  if not red then
    return
  end
  -- 释放连接（连接池实现）
  local pool_max_idle_time = 1000 * 10 -- 毫秒
  local pool_size = 100 --连接池大小
  local ok, err = red:set_keepalive(pool_max_idle_time, pool_size)
  if not ok then
    ngx.say("set keepalive error : ", err)
  end
end

-- 读取对象
function RedisTemplate.getObject(key)
  local red = initConnect();

  if red == nil then
    ngx.log(ngx.ERR, "red: 为nil")
    ngx.exit(ngx.HTTP_UNAUTHORIZED);
  end

  if key == nil then
    ngx.log(ngx.ERR, "key不存在")
    ngx.exit(ngx.HTTP_UNAUTHORIZED);
  end

  local res, err = red:get(key)
  if res == ngx.null or not res then
    ngx.log(ngx.ERR, "redis中没有找到：err:", err, " res:", res)
    ngx.log(ngx.WARN, "Redis Missing token")
    ngx.exit(ngx.HTTP_UNAUTHORIZED)
  end
  closeConnect(red);
  return res;
end


-- 存入对象
function RedisTemplate.setObject(key, value)
  local red = initConnect();

  if red == nil then
    ngx.exit(ngx.HTTP_UNAUTHORIZED);
  end

  if key == nil then
    ngx.log(ngx.ERR, "key不存在")
    ngx.exit(ngx.HTTP_UNAUTHORIZED);
  end

  if value == nil then
    ngx.log(ngx.ERR, "value不存在")
    ngx.exit(ngx.HTTP_UNAUTHORIZED);
  end

  --red:init_pipeline()

  red:set(key, value)
  --
  --local results, e = red:commit_pipeline()
  --if not results then
  --  ngx.log(ngx.INFO, "请求提交失败: ", e)
  --  return nil;
  --end
  return key;
end


-- 存入对象
function RedisTemplate.setIncr(key, value)
  local red = initConnect();

  if red == nil then
    ngx.exit(ngx.HTTP_UNAUTHORIZED);
  end

  if key == nil then
    ngx.log(ngx.ERR, "key不存在")
    ngx.exit(ngx.HTTP_UNAUTHORIZED);
  end

  if value == nil then
    ngx.log(ngx.ERR, "value不存在")
    ngx.exit(ngx.HTTP_UNAUTHORIZED);
  end

  --red:init_pipeline()

  red:incr(key)
  --
  --local results, e = red:commit_pipeline()
  --if not results then
  --  ngx.log(ngx.INFO, "请求提交失败: ", e)
  --  return nil;
  --end
  closeConnect(red);
  return key;
end

return RedisTemplate;